package com.hejielife.readwritelock2;

/**
 * 2019年8月2日 下午3:29:40
 * 
 * @author hejielife
 * @despribe ReadWriteLock
 */

public final class ReadWriteLock {
	private int readingReaders = 0;
	private int waitingWriters = 0;
	private int writingWriters = 0;
	private boolean preferWriter = true;

	public synchronized void readLock() throws InterruptedException {
		while (writingWriters > 0 || (preferWriter && waitingWriters > 0)) {
			wait();
		}
		readingReaders++;
	}

	public synchronized void readUnlock() {
		readingReaders--;
		preferWriter = true;
		notifyAll();
	}

	public synchronized void writeLock() throws InterruptedException {
		waitingWriters++; // (B)���ڵȴ�д����߳�������1
		try {
			while (readingReaders > 0 || writingWriters > 0) {
				wait();
			}
		} finally {
			waitingWriters--; // (B)���ڵȴ�д����߳�������1
		}
		writingWriters++; // (C)ʵ������д����߳�������1
	}

	public synchronized void writeUnlock() {
		writingWriters--; // (C)ʵ������д����߳�������
		preferWriter = false;
		notifyAll();
	}
}
